<template>
  <div class="login-container">
    <div class="login-box">
      <div class="title-box"><h3>后台管理系统</h3></div>
      <el-form :model="loginfrom" ref="loginRef" :rules="loginrules">
        <el-form-item prop="username">
          <el-input
            v-model="loginfrom.username"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input type="password" v-model="loginfrom.password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loginFn">登录</el-button><br/>
          <el-link type="info" @click="$router.push('/reg')">去注册</el-link>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { loginAPI } from '@/api'
import { mapMutations } from 'vuex'
export default {
  name: 'my-login',

  data () {
    return {
      loginfrom: {
        username: '',
        password: ''
      },
      loginrules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { pattern: /^[a-zA-Z1-9]{4,10}$/, message: '用户名必须4-10位的字母或数字', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { pattern: /^\S{6,15}$/, message: '密码必须是6-15位的非空字符', trigger: 'blur' }
        ]
      }
    }
  },

  mounted () {},

  methods: {
    ...mapMutations(['updateToken']),
    loginFn () {
      this.$refs.loginRef.validate(async valid => {
        if (valid) {
          const { data: res } = await loginAPI(this.loginfrom)
          if (res.status !== 0) return this.$message.error(res.message)
          this.$message.success(res.message)
          this.updateToken(res.token)
          this.$router.push('/')
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.login-container {
  background: url("../../assets/bg1.jpg") center;
  background-size: cover;
  height: 100%;
  .login-box {
    width: 400px;
    height: 335px;
    background-color:rgb(255 255 255 / 84%);
    border-radius: 3px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    padding: 0 30px;
    box-sizing: border-box;
    .title-box {
      height: 60px;
      h3 {
        text-align: center;
      }
    }
    .el-button{
      width: 100%;
    }
    .el-link{
      font-size: 10px;
    }
    .el-form-item{
      margin-bottom: 18px;
    }
  }
}
</style>
